import { VscodeMsgPoster } from '@/utils/MessageHelper';
export enum CfgType {
  OS,
  APP,
  MSL
}

interface CfgData {
  data: Record<string, unknown>;
}

export const cfgData: CfgData = {
  data: {}
};

export let cfgMetadata: ICfgMetadata;

export const setCfgData = (val: Record<string, unknown>) => {
  cfgData.data = val;
};

export function setCfgMetadata(md: ICfgMetadata) {
  cfgMetadata = md;
}

// 参数path为treeData中的path，但是和cfg数据格式基本一致（在数组上稍有处理）
function findCfgNode(path: string) {
  let data = cfgData.data.configure;
  const tokens = (path as string).split('/').filter(item => !!item);
  tokens.forEach(t => {
    const tTokens = t.split('_');
    if (tTokens.length === 3) {
      const idx = tTokens[2];
      const key = tTokens[0];
      data = (data as any)[key];
      if (Array.isArray(data)) {
        data = (data as any)[idx];
      }
    } else {
      data = (data as any)[t];
    }
  });
  return data;
}

// 更新cfg 属性
export function updateCfgAttr(curNode: any, attrItem: any) {
  const { path } = curNode;
  const data = findCfgNode(path);
  const { name, value } = attrItem;
  (data as any)[`@_${name}`] = value;
  VscodeMsgPoster.updateData(cfgData.data);
}

function disableCfgNodeAndChildren(data: any) {
  if (Array.isArray(data)) {
    data.forEach(d => {
      disableCfgNodeAndChildren(d);
    });
  } else {
    if (data['@_enable'] === 'false') {
      return;
    }
    data['@_enable'] = 'false';
    for (const key in data) {
      if (Object.prototype.hasOwnProperty.call(data, key) && !key.startsWith('@_')) {
        disableCfgNodeAndChildren(data[key]);
      }
    }
  }
}

// 更新 cfg enable 状态
export function updateEnableStatus2Cfg(updatedData: any[]) {
  updatedData.forEach(curNode => {
    const { path, enable } = curNode;
    const data = findCfgNode(path) as any;
    if (enable === 'false') {
      // 如果存在enable属性
      disableCfgNodeAndChildren(data);
    } else {
      // 如果不存在enable属性
      delete data['@_enable'];
    }
  });
  console.log('cfg data: ', cfgData.data);
  VscodeMsgPoster.updateData(cfgData.data);
}
